package cz.proks.schoolpupilbook.gwt.core.handler;

import java.util.Date;

import com.google.gwt.user.client.Window;

import cz.proks.schoolpupilbook.gwt.core.ResultNotifiable;
import cz.proks.schoolpupilbook.gwt.service.MarkCommentService;
import cz.proks.schoolpupilbook.gwt.service.ServiceFactory;
import cz.proks.schoolpupilbook.gwt.widget.common.LectorView.CommentSubmitEvent;
import cz.proks.schoolpupilbook.gwt.widget.common.ParentView;
import cz.proks.schoolpupilbook.gwt.widget.common.LectorView;
import cz.proks.schoolpupilbook.shared.domain.Mark;
import cz.proks.schoolpupilbook.shared.domain.MarkComment;

public class CommentSubmitHandler implements ParentView.CommentSubmitEvent.CommentSubmitHandler,
											 LectorView.CommentSubmitEvent.CommentSubmitHandler {

	@Override
	public void onNewComment(ParentView.CommentSubmitEvent event) {		
		MarkComment markComment = createMarkComment(event);
		saveMarkComment(markComment);
	}
		
	@Override
	public void onNewComment(LectorView.CommentSubmitEvent event) {
		MarkComment markComment = createMarkComment(event);
		saveMarkComment(markComment);
	}
	
	private void saveMarkComment(MarkComment markComment) {
		MarkCommentService markCommentService = ServiceFactory.getMarkCommentService();
		markCommentService.save(markComment, new ResultNotifiable<Void>() {
			
			@Override
			public void onSucces(Void object) {
				
			}
			
			@Override
			public void onError(Throwable t) {
				Window.alert("Communication failed: " + t.getLocalizedMessage());
				
			}
		});
	}


	private MarkComment createMarkComment(ParentView.CommentSubmitEvent event) {
		MarkComment markComment = new MarkComment();
		Mark mark = new Mark();
		mark.setId(event.getMark().getId());
		
		markComment.setId(null);
		markComment.setMark(mark);
		markComment.setTime(new Date());
		markComment.setContributor(event.getUser());
		markComment.setComment(event.getComment());
		
		return markComment;
	}
	
	private MarkComment createMarkComment(LectorView.CommentSubmitEvent event) {
		MarkComment markComment = new MarkComment();
		Mark mark = new Mark();
		mark.setId(event.getMark().getId());
		
		markComment.setId(null);
		markComment.setMark(mark);
		markComment.setTime(new Date());
		markComment.setContributor(event.getUser());
		markComment.setComment(event.getComment());
		
		return markComment;
	}

}
